package com.zjmcollege.hotpot.search.model;

import lombok.extern.slf4j.Slf4j;
import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.Configurable;
import org.hibernate.id.IdentifierGenerator;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.type.Type;

import java.io.*;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.time.LocalDateTime;
import java.util.Properties;

/**
 * @author zpym
 * @CopyRight (C) http://www.iengoo.com
 * @brief
 * @email 122162005@qq.com
 * @date 2019-11-11 09:42
 */
@Slf4j
public class IdGenerator implements Configurable, IdentifierGenerator {
    private int idLength = 20;

    @Override
    public void configure(Type type, Properties properties, ServiceRegistry serviceRegistry) throws MappingException {
        // 获取传入的参数
        String length = (String) properties.getOrDefault("idLength", "20"); // 默认自定义生成id的长度为15
        // 如果参数小于默认长度20，则不使用传入参数，而是使用默认参数
        if (Integer.parseInt(length) > idLength) {
            this.idLength = Integer.parseInt(length);
        }
    }

    @Override
    public Serializable generate(SharedSessionContractImplementor sharedSessionContractImplementor, Object o) throws HibernateException {
        // 生成长度为20的字符串作为id
        LocalDateTime now = LocalDateTime.now();
        StringBuffer buffer = new StringBuffer(5);

        buffer.append(now.getYear());  // 4位
        buffer.append(String.format("%02d", now.getMonthValue())); // 补齐为2位
        buffer.append(String.format("%02d", now.getDayOfMonth())); // 补齐为2位
        buffer.append(String.format("%09d", now.getNano()));       // 补齐为9位

        if (buffer.length() < idLength) {
            int length = idLength - buffer.length();
            buffer.append(String.format("%0" + length + "d", (int) (Math.random() * 100)));
        }

        return buffer.toString();
    }

    public static void main(String[] args) throws UnknownHostException {
        // readall("D:/fileserver/md/f4da4857847a407bb701247edc74cd2e.md");
    }
}
